﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp2
{
    class DbHelper
    {

        public static readonly string comString = "server=.;database=Blogs;uid=sa;pwd=123123";

        public static SqlConnection contt;

        public static DataTable GetDataTable(string sql)
        {
            SqlConnection sqlConnection = new SqlConnection(comString);

            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql,sqlConnection  );


            DataTable data = new DataTable();

            sqlConnection.Open();
            sqlDataAdapter.Fill(data);
            return data;


        }

        public static int AddOrEdiOrDeleteSava(string sql)
        {
            SqlConnection sqlConnection = new SqlConnection(comString);
            SqlCommand command = new SqlCommand(sql, sqlConnection);

            sqlConnection.Open();

            return command.ExecuteNonQuery();
        }
        public static void OpenConn()
        {
            string SqlCon = comString;
            contt  = new SqlConnection(SqlCon);
            if (contt .State.ToString().ToLower() == "open")
            {
            }
            else
            {
                contt .Open();
            }
        }

        public static void CloseConn()
        {
            if (contt .State.ToString().ToLower() == "open")
            {
                contt .Close();
                contt .Dispose();
            }
        }
        public int SqlServerRecordCount(string sql)
        {
            OpenConn();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = sql;
            cmd.Connection = contt ;
            SqlDataReader dr = cmd.ExecuteReader();
            int RecordCount = 0;
            while (dr.Read())
            {
                RecordCount = RecordCount + 1;
            }
            CloseConn();
            return RecordCount;
        }

        public void ExecuteNonQuery(string sql)
        {
            OpenConn();
            SqlCommand cmd = new SqlCommand(sql, contt );
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            CloseConn();
        }
    }
}
